const begin = document.querySelector('.begin');//开始界面
const cover = document.querySelector('.cover');//遮罩
const button1 = document.querySelector('#button-1');//开始

const recruit = document.querySelector('.recruit');//雇佣界面
const add = document.querySelector('.addcooker1');//触发雇佣
const button2 = document.querySelector('#button-2');//雇佣
const button3 = document.querySelector('#button-3');//不雇佣

const fire = document.querySelector('.fire');//解雇界面
const button4 = document.querySelector('#button-4');//解雇
const button5 = document.querySelector('#button-5');//不解雇
let fireWho;
const cooker = document.querySelector('.cooker');//厨师界面
const guest = document.querySelector('.guest');//顾客

const wait = document.querySelector('.waitting');//等待区
let weekend = document.getElementById("weekend");//周数
let day = document.getElementById("day");//天数
let income = document.getElementById("income");//收入

let cookerList = [];//厨师列表
let seat = [];//指向座位0,1,2,3
let name = ["Li","Wang","Yan","Liang","Xu","Liu"];//名字
let guestList = [];//顾客对象数组
let waittigQueue = [];//等待队列
let zIndex = 50;
let cash = income.innerText;

//管理者
class Assistant {
    static cookingList = new Array();
    static {
        for(let i=0;i < 4;i++)
            Assistant.cookingList[i] = new Array();
    }
    static displayRecruit() {
        let count = 0;
        for(let i=0;i < 6;i++) {
            if(cookerList[i] != undefined)
                count++;
        }
        if(count === 6)
            return;
        cover.style.display = "flex";
        recruit.style.display = "block";
    }
    static closeRecruit() {
        cover.style.display = "none";
        recruit.style.display = "none";
    }
    static recruit() {
        const newDiv1 = document.createElement('div');
        const newDiv2 = document.createElement('div');
        const newImg = document.createElement('img');
        newDiv1.className = "circle1";
        newDiv1.setAttribute("name","cooker");
        newDiv2.className = "circle2";
        newImg.src = "Images/chef.png";
        newDiv1.addEventListener('dblclick', Assistant.displayFire);
        newDiv1.appendChild(newDiv2);
        newDiv2.appendChild(newImg);
        cooker.insertBefore(newDiv1, add);
        for(let i=0;i < 6;i++) {
            if(cookerList[i] === undefined) {
                cookerList[i] = new Cooker(newDiv1);
                break;
            }
        }
        Assistant.closeRecruit();
    }
    static displayFire(e) {
        fireWho = e.currentTarget;
        cover.style.display = "flex";
        fire.style.display = "block";
    }
    static closeFire() {
        cover.style.display = "none";
        fire.style.display = "none";
    }
    static fire() {
        cash = income.innerText;//起始薪资
        cash -= 140;
        income.innerText = cash;
        cookerList[cookerList.indexOf(fireWho)] = undefined;
        fireWho.remove();
        Assistant.closeFire();
    }
    static arrangeSeat(e) {
        let index = -1;
        for(let i = 0;i < 4;i++) {
            if(seat[i].using === false) {
                index = i;
                break;
            }
        }
        if(index != -1 && e.currentTarget === guestList[waittigQueue[0]].waittingAdress) {
            seat[index].using = true;
            seat[index].address.firstChild.firstChild.style.display = "flex";
            seat[index].address.firstChild.firstChild.src = guestList[waittigQueue[0]].profile;
            seat[index].address.style.display = "flex";
            seat[index].customerNum = waittigQueue[0];
            zIndex++;//恢复层级
            guestList[waittigQueue[0]].waittingAdress.remove();
            waittigQueue.shift();
            Dish.showMenu(seat[index].customerNum, index);
        }
    }
    static arrangeCooker() {
        setInterval(() => {
            for(let i=0;i < 4;i++) {
                for(let j=0;j < Assistant.cookingList[i].length;j++) {
                    for(let k=0;k < 6;k++) {
                        if(cookerList[k] != undefined) {
                            if(cookerList[k].isCooking === false) {
                                let foodname = Dish.dishes[Assistant.cookingList[i][j]].name;
                                let index;
                                for(let m = 0;m < seat[i].food.length;m++) {
                                    if(seat[i].food[m].innerText === foodname) {
                                        index = m;
                                        break;
                                    }
                                }
                                if(seat[i].want[index] != -1) {
                                    cookerList[k].cooking(i, Assistant.cookingList[i][j]);
                                    // Seat.timer(seat[i].food[index]);
                                }
                               Assistant.cookingList[i].shift();
                               j--;
                               break;
                            }
                        }
                    }
                }
            }
        }, 3000);
   }
   static checkPay() {
        setInterval(()=>{
            for(let i=0;i < 4;i++) {
                if(seat[i].cookedfood === seat[i].eatenfood && seat[i].cookedfood != 0 && seat[i].cookedfood != undefined) {
                    let money = document.createElement("div");
                    money.className = "money";
                    seat[i].address.appendChild(money);
                    seat[i].cookedfood =seat[i].eatenfood = 0;
                    seat[i].money = money;
                } 
            }
        }, 9000);
   }
}

Assistant.arrangeCooker();
Assistant.checkPay();

//厨师
class Cooker {
    isCooking = false;
    address;
    constructor (address) {
        this.address = address;
    }
    cooking(seatNumber, foodNumber) {
        this.isCooking = true;
        let Div = document.createElement("div");
        Div.className = "cooking foodsingle";
        Div.innerHTML = Dish.dishes[foodNumber].name;
        this.address.appendChild(Div);
        Cooker.timer(Div);
        setTimeout(() => {
            let name = Div.innerHTML;
            Div.remove();
            this.isCooking = false;
            let food = seat[seatNumber].food;
            for(let i=0;i < food.length;i++) {
                if(name === food[i].innerHTML) {
                    if(seat[seatNumber].want[i] == -1)
                        break;
                    seat[seatNumber].want[i] = 1;
                    seat[seatNumber].cookedfood++;
                    seat[seatNumber].eating();
                    let img = document.createElement("img");
                    food[i].appendChild(img);
                    break;
                }
            }
        }, 3000);
    }
    static timer(target) {
        let pre = performance.now();
        let num = 0;
        let f = setInterval(() => {
            let now = performance.now();
            num += (now - pre)/30;
            pre = now;
            let s = String(num);
            target.style.background = "linear-gradient(to right,red 0%,red "+s+"%,blue "+s+"%,blue 100%)";
            if(num >= 100)
                clearInterval();
        }, 30)
    }
}

{
    for(let i=0;i < 6;i++) {
        cookerList.push(undefined);
    }
    let temp = document.querySelector(".must");
    cookerList[0] = (new Cooker(temp));
}

//顾客
class Guest {
    name;//姓名
    profile;//头像
    waittingAdress;//等待地址
    constructor(name, profile) {
        this.name = name;
        this.profile = profile;
    }
    wait(i) {
        zIndex--;//降低层级
        const newDiv1 = document.createElement('div');
        const newDiv2 = document.createElement('div');
        const newP = document.createElement('p');
        const newImg = document.createElement('img');
        newDiv1.className = "circle1";
        newDiv1.style.zIndex = zIndex;
        newDiv2.className = "circle2";
        newP.innerHTML = "等位中";
        this.div = newDiv1;
        newImg.src = this.profile;
        newDiv1.appendChild(newDiv2);
        newDiv1.appendChild(newP);
        newDiv2.appendChild(newImg);
        wait.appendChild(newDiv1);
        guestList[i].waittingAdress = newDiv1;
        waittigQueue.push(i);
        for(let i = 0;i < waittigQueue.length;i++) {
            guestList[waittigQueue[i]].waittingAdress.style.right =  String(80*(waittigQueue.length-i-1))+"px";
        }
        newDiv1.addEventListener('click', Assistant.arrangeSeat);
    }
    static waitFood(seatNumber, foodNumber) {
        setTimeout(()=> {
            if(seat[seatNumber].want[foodNumber] == 0) {
                seat[seatNumber].want[foodNumber] = -1;
                seat[seatNumber].food[foodNumber].style.textDecoration="line-through";
            }
        }, 8000);
    }
    leave(e) {
        let i = 0;
        for(;seat[i].address != e.currentTarget;i++)
                ;
        if(seat[i].using === false)
            return;
        if(e.target != seat[i].money) {
           for(let j = 0;j < seat[i].food.length;j++) {
                if(seat[i].want[j] != -1) {
                    return;
                }
            }
        }else {
            e.target.remove();
        }
        let food = seat[i].food;
        seat[i].using = false;
        income.innerHTML = parseInt(income.innerHTML) + (new Guest).pay(i);
        e.currentTarget.firstChild.firstChild.style.display = "none";
        for(let j=food.length;j >= 1;j--) {
            food.pop().remove();
            seat[i].want.pop();
        }
    }
    pay(i) {
        let food = seat[i].food;
        let sum = 0;
        for(let j = 0;j < food.length;j++) {
            if(seat[i].want[j] == 1)
                sum += Dish.singleFoodPrice(food[j].innerText);
        }
        return sum;
    }
}

//初始化顾客
for(let i=1;i <= 6;i++) {
    guestList.push(new Guest(name[i-1],"Images/customer"+i+".png"));
}

//日期与周期
let Day = document.getElementById('time_D');
let num_D = Day.innerText;
let Week = document.getElementById('time_W');
let num_W = Week.innerText;
let num_cook = 0;
let cnt = 2;

guestList[0].wait(0);
guestList[1].wait(1);
//关闭开始界面
button1.addEventListener('click', () => {
    cover.style.display = "none";
    begin.style.display = "none";
    setInterval(function () {
        num_D++;
        Day.innerText = num_D;
        if (num_D % 8 === 0) {
            for (let i = 0; i < cookerList.length; i++) {
                if(cookerList[i]!=undefined){
                    num_cook++;
                }
            }
            cash -= num_cook*100;
            income.innerText = cash;
            num_D = 1;
            Day.innerText = num_D;
            num_W++;
            Week.innerText = num_W;
        }
    }, 24000);
    setInterval(function () {
        if(cnt % 6===0&&cnt != 0){
            cnt = 0;
        } else{
            if(waittigQueue.length>=3) {
                return;
            } else {
                guestList[cnt].wait(cnt);
                cnt++;
            }
        }
    },10000);
});

// 此处的方法不要加括号,调用的是方法名
//招聘厨师
//点击加号，厨师最多6人
add.addEventListener('click', Assistant.displayRecruit);
button2.addEventListener('click', Assistant.recruit);
button3.addEventListener('click', Assistant.closeRecruit);

// 厨师弹出解雇
//双击解雇
button4.addEventListener('click', Assistant.fire);
button5.addEventListener('click', Assistant.closeFire);

//座位类
class Seat {
    money = undefined;
    eatenfood;
    seatNumber;
    cookedfood;
    want = []
    food = [];
    customerNum;
    constructor(address,seatNumber) {
        this.address = address;
        this.using = false;
        this.seatNumber = seatNumber;
    }
    waitFood() {
        this.cookedfood = 0;
        this.eatenfood = 0;
        for(let i=0;i < this.food.length;i++) {
            this.want[i] = 0;
            Seat.timer(this.food[i]);
            Guest.waitFood(this.seatNumber, i);
        }
    }
    eating() {
        setTimeout(()=>{
            this.eatenfood++;
        }, 3000);
    }
    static timer(target) {
        let pre = performance.now();
        let num = 0;
        let f = setInterval(() => {
            let now = performance.now();
            num += (now - pre)/30;
            pre = now;
            let s = String(num);
            target.style.background = "linear-gradient(to right,green 0%,green "+s+"%,blue "+s+"%,blue 100%)";
            if(num >= 100)
                clearInterval();
        }, 30)
    }
}

//座位
{
    let temp = document.getElementsByName("seat");
    for(let i=0;i < 4;i++) {
        seat.push(new Seat(temp[i], i));
    }
}

//注册离开事件
seat.forEach((item)=>{
    item.address.addEventListener('dblclick',(new Guest).leave);
})

/*----------------------------------------------------*/
/*菜品*/
class Dish {
    static dishes = {
        0: {
            name: "凉拌SAN",
            type: "liangCai",
            price: 6
        },
        1: {
            name: "冷切DOM",
            type: "liangCai",
            price: 4
        },
        2: {
            name: "UL抄LI",
            type: "zhuCai",
            price: 12
        },
        3: {
            name: "红烧HEAD",
            type: "zhuCai",
            price: 15
        },
        4: {
            name: "酥炸Table",
            type: "zhuCai",
            price: 18
        },
        5: {
            name: "炙烤CSS",
            type: "zhuCai",
            price: 16
        },
        6: {
            name: "清蒸DIV",
            type: "zhuCai",
            price: 12
        },
        7: {
            name: "鲜榨flex",
            type: "yinPin",
            price: 5
        },
        8: {
            name: "小程序奶茶",
            type: "yinPin",
            price: 6
        }
        };

        /*打开菜单*/
        static showMenu(id, seatNumber) {
            const menu = document.querySelector(".Menu");
            menu.style.display = "flex";
            cover.style.display = "flex";
            const order = document.getElementById("order");//点好了
            const quit = document.getElementById("quit");//不点了
            const menuImg = document.getElementById("menu_pic");
            const list = document.getElementsByName("menu");
            let menuId = document.getElementById("menu_title");
            menuImg.src = guestList[id].profile;
            let text = guestList[id].name + "正在点菜,已点0元的菜";
            menuId.innerHTML = text;
            //order.setAttribute("style", "background: linear-gradient(180deg, #ded3ba 50%, #d3c6a5 50%);border: 3px solid #938867;color: #938867;");
            //所有选项开始时均置为未选状态
            list.forEach((item) => {
                item.checked = false;
            })
            list.forEach((item) => {
                item.addEventListener('change', () => {
                    Dish.handleMenu(id);
                })
            })
            
            const newQuitButtonListener = () => {
                console.log(seatNumber);
                Dish.quitOrdering(seatNumber);
                quit.removeEventListener('click', newQuitButtonListener);
                order.removeEventListener('click',newSubmitButtonListener);
            };

            quit.addEventListener('click', newQuitButtonListener);

            const newSubmitButtonListener = () => {
                if(Dish.menuCanUse()) {
                    Dish.finishOrder(id, seatNumber);
                    order.removeEventListener('click',newSubmitButtonListener);
                    quit.removeEventListener('click', newQuitButtonListener);
                }
            };
            order.addEventListener('click', newSubmitButtonListener);
        }

        static quitOrdering(seatNumber) {
            const menu = document.querySelector(".Menu");
            seat[seatNumber].using = false;
            menu.style.display = "none";
            cover.style.display = "none";
            seat[seatNumber].address.firstChild.firstChild.style.display = "none";
        }

        /*单品收银*/
        static singleFoodPrice(foodName) {
            for (let i = 0;i <= 8;i++) {
                if (Dish.dishes[i].name === foodName) {
                    return Dish.dishes[i].price;
                }
            }
        }
        /*处理菜单*/
        static handleMenu(id) {
            let totalPrice = 0;
            let order = document.getElementById("order");
            let menuId = document.getElementById("menu_title");
            const list = document.getElementsByName("menu");
            for (let i=0;i < list.length;i++) {
                if (list[i].checked === true) {
                    totalPrice += parseInt(list[i].value);
                }
            }
            let text = guestList[id].name + "正在点菜，已点" + totalPrice + "元的菜";
            menuId.innerHTML = text;
        }
        /*菜单校验*/
        static menuCanUse() {
            const list = document.getElementsByName("menu");
            let liangCai = 0,
                zhuCai = 0,
                drinking = 0;
            for (let i in list) {
                if (i < 2) { //凉菜
                    if (list[i].checked === true) {
                        liangCai++;
                    }
                } else if (i < 7) { //主菜
                    if (list[i].checked === true) {
                        zhuCai++;
                    }
                } else { //饮品
                    if (list[i].checked === true) {
                        drinking++;
                    }
                }
            }
            if (liangCai <= 1 && zhuCai === 1 && drinking <= 1) {
                return true;
            }
            return false;
        }
        
        /*完成点菜*/
        static finishOrder(id, seatNumber) {
            const list = document.getElementsByName("menu");
            for (let i=0;i < list.length;i++) {
                if (list[i].checked === true) {
                    Assistant.cookingList[seatNumber].push(i); //将菜号加入到菜表
                }
            }
            let food = Assistant.cookingList[seatNumber];
            let parent = document.getElementsByName("food");
            for (let i=0;i < food.length;i++) {
                let div1 = document.createElement("div");
                div1.className = "foodsingle";
                div1.innerHTML = Dish.dishes[food[i]].name;
                seat[seatNumber].food.push(div1);
                parent[seatNumber].appendChild(div1);
            }
            let menu = document.querySelector(".Menu");
            menu.style.display = "none";
            cover.style.display = "none";
            seat[seatNumber].waitFood();
        }
}